<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\TcmBookChapter;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Cache;

class TcmBookChapterController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new TcmBookChapter(['book']), function (Grid $grid) {
            $grid->model()->orderByDesc('id')->orderBy('sort');
            $grid->column('id');
            $grid->column('book_id');
            $grid->column('book.name', '书籍名称');
            $grid->column('name');
            $grid->column('playable')->using(['否', '是'])->label(['warning', 'primary']);
            $grid->column('subhead');
            $grid->column('volume');
            $grid->column('sort');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();

                $filter->equal('id')->width(3);
                $filter->equal('book_id')->width(3);
                $filter->like('name')->width(3);
                $filter->between('created_at')->datetime()->width(4);
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new TcmBookChapter(), function (Show $show) {
            $show->field('id');
            $show->field('book_id');
            $show->field('name');
            $show->field('playable');
            $show->field('subhead');
            $show->field('volume');
            $show->field('audio');
            $show->field('content');
            $show->field('sort');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new TcmBookChapter(), function (Form $form) {
            $form->display('id');
            $form->select('book_id')->options(\App\Models\TcmBook::pluck('name', 'id')->all());
            $form->text('name');
            $form->radio('playable')->options(['否', '是']);
            $form->text('subhead');
            $form->text('volume');
            $form->file('audio')->chunked()->chunkSize(1024 * 5)->maxSize(1024 * 2 * 1000)->autoUpload()->uniqueName()->saveFullUrl();;
            $form->textarea('describe');
            $form->ueditor('content');
            $form->number('sort')->default(0);

            $form->saved(function (Form $form) {
                Cache::forget('BOOK_CHAPTER_' . $form->getKey());
            });
        });
    }
}
